package com.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.upload.constant.SplitConstant;

public class DeleteServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 201805081622162L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 得到要下载的文件名
		String fileName = request.getParameter("filename"); // 23239283-92489-阿凡达.avi
		// fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
		// 上传的文件都是保存在/WEB-INF/upload目录下的子目录当中
		String fileSaveRootPath = this.getServletContext().getRealPath("/WEB-INF/upload");
		// 通过文件名找出文件的所在目录
		String path = findFileSavePathByFileName(fileName, fileSaveRootPath);
		// 得到要下载的文件
		File file = new File(path + "\\" + fileName);
		// 如果文件不存在
		if (!file.exists()) {
			request.setAttribute("message", "您要刪除的资源不存在！！");
			request.getRequestDispatcher("//message.jsp").forward(request, response);
			return;
		}
		
		file.delete();
		
		request.setAttribute("message", "文件刪除成功！！");
		request.getRequestDispatcher("/message.jsp").forward(request, response);
	}

	public String findFileSavePathByFileName(String filename, String saveRootPath) {
		// int hashcode = filename.hashCode();
		// int dir1 = hashcode & 0xf; // 0--15
		// int dir2 = (hashcode & 0xf0) >> 4; // 0-15
		// String dir = saveRootPath + "\\" + dir1 + "\\" + dir2; // upload\2\3

		String[] filenames = filename.split(SplitConstant.SPLIT_SYMBOL);
		String dir = saveRootPath + "\\" + filenames[1]; // upload\2\3
															// upload\3\5//
															// upload\3\5
		File file = new File(dir);
		if (!file.exists()) {
			// 创建目录
			file.mkdirs();
		}
		return dir;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}